package com.zhj.demo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhj.demo.base.AppUtils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.Util;
import okhttp3.internal.cache.CacheInterceptor;
import okhttp3.internal.cache.CacheRequest;
import okhttp3.internal.cache.CacheStrategy;
import okhttp3.internal.cache.InternalCache;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.http.HttpMethod;

import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static okhttp3.Protocol.HTTP_1_1;
import static okhttp3.internal.Util.closeQuietly;


public class MainActivity extends AppCompatActivity {
    ImageView imageview;
    Button btnList;
    Button btnScheme;

    Button btnNetwork;
    TextView tvContent;
    Button btnClear;


    OkHttpClient okHttpClient;

    String url = "https://partner.to.network/icms-io/api/discovery/getDiscoveryPageSettings";
//    String url = "http://www.qq.com";


    //从百度翻译抓过来的接口
    public static final String URL_EXTEND_TRANS = "http://fanyi.baidu.com/extendtrans";
    public static final String URL_TRANSLATE = "http://fanyi.baidu.com/translate#zh/en";
    public static final String URL_BASETRANSLATE = "http://fanyi.baidu.com/basetrans";
    public static final String URL_LANGDETECT = "http://fanyi.baidu.com/langdetect";



    @SuppressLint("HandlerLeak")
    Handler uiHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 100:
                    tvContent.setText(msg.obj.toString());
                    break;
                case 222:
                    tvContent.setText("访问失败: " + msg.obj.toString());
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageview = findViewById(R.id.image);
        btnList = findViewById(R.id.btn_list_view);
        btnScheme = findViewById(R.id.btn_scheme);

        btnNetwork = findViewById(R.id.btn_network);
        tvContent = findViewById(R.id.tv_content);
        btnClear = findViewById(R.id.btn_clear);


        String name = "默认";
        Intent intent = getIntent();
        if(intent != null){
            if(intent != null){
                name = intent.getStringExtra("name");
            }
        }

        Log.d("zhj77", " onCreate name=" + name);



        AppUtils.init(this);

        imageview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rotateAnim();
            }
        });

        btnList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, RecyclerTestActivity.class);
                startActivity(intent);
            }
        });


        btnScheme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onScheme();
            }
        });

        btnNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onNetwork();
            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvContent.setText("");
            }
        });

        initData();
    }



    private void initData() {
        ///storage/emulated/0/Android/data/com.zhj.demo/cache/zhj
        File cacheFile = new File(getExternalCacheDir(),"zhj");
        Cache cache = new Cache(cacheFile,1024*1024*50);

        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .cache(cache)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Request newRequest = request.newBuilder()
                                .header("cache-control","public")
                                .build();

                        return chain.proceed(newRequest);
                    }
                })

                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {

                        Request request = chain.request();
                        if(!AppUtils.isNetworkConnected(MainActivity.this)){ // 直接读缓存
                            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
                        }

                        return chain.proceed(request);
                    }
                })

                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Response response = chain.proceed(chain.request());
                        Response newResponse = response.newBuilder()
                                .removeHeader("pragma")
                                .header("Cache-Control","max-age=6000")
                                .build();
                        return newResponse;
                    }
                })


                .build();
    }

    private void onNetwork() {
        CacheControl cacheControl = new CacheControl.Builder()
                .maxAge(1000,TimeUnit.MINUTES)
                .noCache()
                .build();


        final Request request = new Request.Builder()
                .addHeader("b-token","7ykG2SdsBrna5FVcHWwxRcUuNhz4uPM87wLXxXxNe9rR")
                .addHeader("b-client","android-1.7.0")
                .addHeader("Content-Type", "application/json")
                .method("GET",null)
                .url(url)
                .cacheControl(cacheControl)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() == 200){
                    Message message = uiHandler.obtainMessage();
                    message.what = 100;
                    message.obj = response.body().string();
                    uiHandler.sendMessage(message);
                }else {
                    Message message = uiHandler.obtainMessage();
                    message.what = 222;
                    message.obj = "错了";
                    uiHandler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Message message = uiHandler.obtainMessage();
                message.what = 222;
                message.obj = e.getLocalizedMessage();
                uiHandler.sendMessage(message);
            }
        });
    }


    private void onScheme() {
        Uri uri = Uri.parse("biyong://authorApp?url=http://user.emoding.com/oauth/callback-authtoken.action&merchantid=7f4e8c147af94a4f0fff20854ce11a7b");
        Intent action = new Intent(Intent.ACTION_VIEW,uri);
        startActivityForResult(action,9090);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Uri uri =  intent.getData();

        Log.d("zhj77", " url=" + uri.toString());

        Toast.makeText(this,"url=" + uri.toString(),Toast.LENGTH_LONG).show();


        /**
         * 另一方在结束的时候调用这个就行了
         Uri uri = Uri.parse("zhj://jiulu.com/name/tom");
         Intent intent2 = new Intent(Intent.ACTION_VIEW,uri);
         startActivity(intent2);
         */
    }

    public void rotateAnim() {
        Animation anim = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        anim.setFillAfter(true); // 设置保持动画最后的状态
        anim.setDuration(3000); // 设置动画时间
        anim.setInterpolator(new AccelerateInterpolator()); // 设置插入器
        imageview.startAnimation(anim);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String name = "默认";
        if(data != null){
            name = data.getStringExtra("name");
        }


        Log.d("zhj77","requestCode=" + requestCode +  "resultCode=" + resultCode + " name=" + name);

    }

    /**
     * 探测语言
     */
    public void langDetect(String content, Map<String, String> header, String cookie) {
        Request.Builder builder = new Request.Builder();

        String query = content;
        if (content != null && content.length() > 20) {
            query = content.substring(0, 20);
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), "query=" + query);
        builder.url(URL_LANGDETECT);

        try {
            //1 添加header
            if (header != null && !header.isEmpty()) {
                Iterator iter = header.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String key = (String) entry.getKey();
                    String val = (String) entry.getValue();
                    builder.header(key, val);
                }
            }

            //2 添加cookie
            builder.header("Cookie","PSTM=1499762712; BIDUPSID=3C3AA6CA2CCC1B4D1FD9C0B3629E7875; BDUSS=dwQ1VJLWsxdFN6ZWZnfm56R1FLazR4bUhFTU1rQkxWU0VFLWxraUszbHJjcGRhQVFBQUFBJCQAAAAAAAAAAAEAAAAuXV0FYmFsdWRlamlhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGvlb1pr5W9aSD; MCITY=-131%3A; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; BAIDUID=B8CE0C9C7711D9B323AE471B30D2204D:FG=1; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; locale=zh; PSINO=7; H_PS_PSSID=1423_21093_26350_26923; to_lang_often=%5B%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%2C%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%5D; from_lang_often=%5B%7B%22value%22%3A%22en%22%2C%22text%22%3A%22%u82F1%u8BED%22%7D%2C%7B%22value%22%3A%22zh%22%2C%22text%22%3A%22%u4E2D%u6587%22%7D%5D; Hm_lvt_afd111fa62852d1f37001d1f980b6800=1534040079,1534055333; Hm_lpvt_afd111fa62852d1f37001d1f980b6800=1534055333; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1534040058,1534040066,1534055295,1534055333; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1534055333");
            builder.post(body);
        }catch (Exception e){

        }

        final Request request = builder.build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {


            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


            }
        });
    }
}

